#include "chatserver.hpp"
#include "chatservice.hpp"
#include <functional>
#include <string>
#include "json.hpp"

using namespace std;
using namespace placeholders;
using json = nlohmann::json;

/**
 * @brief 聊天服务器构造方法
 *
 * @param loop
 * @param listenAddr
 * @param nameArg
 */
ChatServer::ChatServer(EventLoop *loop,
                       const InetAddress &listenAddr,
                       const string &nameArg)
    : _server(loop, listenAddr, nameArg), _loop(loop)
{
    // 设置服务器连接回调
    _server.setConnectionCallback(
        bind(&ChatServer::onConnection, this, _1));
    // 注册用户读写实现回调
    _server.setMessageCallback(
        bind(&ChatServer::onMessage, this, _1, _2, _3));
    // 设置服务器线程数量
    _server.setThreadNum(4);
}
/**
 * @brief 启动tcp服务器
 *
 */
void ChatServer::start()
{
    _server.start();
}
/**
 * @brief 链接事物的处理
 *
 * @param conn
 */
void ChatServer::onConnection(const TcpConnectionPtr &conn)
{
    if (!conn->connected())
    {
        ChatService::getInstance()->clientCloseException(conn);
        conn->shutdown();
    }
}
/**
 * @brief 读写事件的处理
 *
 * @param conn
 * @param buffer
 * @param time
 */
void ChatServer::onMessage(const TcpConnectionPtr &conn,
                           Buffer *buffer,
                           Timestamp time)
{
    // 接收到所有的消息，然后回显
    string buf(buffer->retrieveAllAsString());
    json js = json::parse(buf);
    auto msgHandler = ChatService::getInstance()->getHandler(js["msgid"].get<int>());
    msgHandler(conn, js, time);
}
